let text = require('../../../../common/util/text.js')
const app = getApp()
Page({
  data: {
    productList:[],
    ispay:'',
    xProduct:'',
    time:'',
    showDetail:-1,
    top:0,
    current:-1,
    xPageReady:true,
    topH:0
  },
  onLoad(options) {
    let that = this
    // let query = wx.createSelectorQuery();
    // query.select('#domHeight').boundingClientRect(rect=>{
    //   let height = rect.height;
    //   that.setData({
    //     top:height+35,
    //     topVal:height+35
    //   })
    // }).exec();
    
    
    that.xInit()
    that.xGetPeriod()
  },
  onShow:function(){
    let that = this
  },
  onUnload() {
    //停止监听
    if (this._observer) this._observer.disconnect()
  },
  onPageScroll(e){
    let that = this
    // 上划
    if(e.scrollTop>that.data.topH){
      let query = wx.createSelectorQuery();
      query.select('#selector0').boundingClientRect(rect=>{
        if(rect.top<0){
          let top = Math.abs(rect.top)
          // rect.height/5
          if(top >= 0){
           if(that.data.current ==0){
              that.setData({
                current:1,
                ispay:that.data.productList[1].need_payment ?'付费':'免费',
              })
            }
          }
        }
        // console.log(rect.height) //元素高度
        // console.log(rect.top)  //元素距离页面顶部的距离
      }).exec();
      query.select('#selector1').boundingClientRect(rect=>{
        if(rect.top<0){
          let top = Math.abs(rect.top)
          if(top >= 0){
            if(that.data.current!=2){
              that.setData({
                current:2,
                ispay:that.data.productList[2].need_payment?'付费':'免费'
              })
            }
          }
        }
      }).exec();
      if(e.scrollTop<=20){
        that.setData({
          current:0,
          ispay:that.data.productList[0].need_payment ?'付费':'免费'
        })
      }
      
    }else{
      let query = wx.createSelectorQuery();
      query.select('#selector1').boundingClientRect(rect=>{
          let top = Math.abs(rect.top)
          if(top >= that.data.topH){
            if(that.data.current==2){
              that.setData({
                current:1,
                ispay:that.data.productList[1].need_payment?'付费':'免费',
              })
            }
          }
      }).exec();
      query.select('#selector0').boundingClientRect(rect=>{
        let top = Math.abs(rect.top)
          if(top >= that.data.topH){
           if(that.data.current ==1){
              that.setData({
                current:0,
                ispay:that.data.productList[0].need_payment ?'付费':'免费',
              })
            }
          }
        // console.log(rect.height) //元素高度
        // console.log(rect.top)  //元素距离页面顶部的距离
      }).exec();
      if(e.scrollTop<=20){
        that.setData({
          current:0,
          ispay:that.data.productList[0].need_payment ?'付费':'免费'
        })
      }
    }
    that.setData({
      topH:e.scrollTop,
      xProduct:that.data.productList[that.data.current]
    })
  },
  xInit:function(){
    let that = this
    wx.cloud.callFunction({
      name: 'product',
      data: {
          action: "get_digital_therapy_product",
          params:{
              is_scheme:true //表示方案类型
          }
      }
    }).then(res => {
        for(let index in res.result){
          if(res.result[index].new_content){
            res.result[index].new_content=text.text(res.result[index].new_content)
          }
        }
        that.setData({
          productList:res.result,
          xPageReady:false
        })
    })
  },
  xGetPeriod:function(){
    let that =this
    wx.cloud.callFunction({
      name: 'product',
      data: {
        action: "get_period_list"
      }
    }).then(res => {
      that.setData({
        time:res.result.camping_period_begin_date?String(res.result.camping_period_begin_date):'',
      })
    })
  },
  // 查看方案详情
  seePlan:function(e){
    let that = this
    let param = e.currentTarget.dataset
    this.setData({
      showDetail:param.index
    })
    // wx.pageScrollTo({
    //   selector: '#selector'+param.index,
    // })
  },
  // 查看方案对比
  xToPlan:function(){
    let that = this
    that.setData({
      show_plan:true
    })
    // setTimeout(function(){
    //   wx.pageScrollTo({
    //    selector:'#plan'
    //   })
    // },300)
  },
  xNoChoose:function(){
    wx.showToast({
      title: '请先选择一个方案',
      icon:'none'
    })
  },
  // 选择方案
  choosePlan:function(e){
    let that= this
    let param = e.currentTarget.dataset
    if(!param.pay && param.count >0 ){
      wx.showToast({
        title: '已加入，无法再次加入',
        icon:'none'
      })
      return
    }
    if(param.pay && param.count >0){
      wx.showToast({
        title: '已购买，无法再次购买',
        icon:'none'
      })
      return
    }
    if(that.data.productList[that.data.productList.length-1].user_order_count>0 && param.index < that.data.productList.length-1 ){
      wx.showToast({
        title: '无法购买',
        icon:'none'
      })
      return
    }
    this.setData({
      current:param.index,
      // isIndexDetail:param.index,
      ispay:param.pay ?'付费':'免费',
      showDetail:param.index,
      xProduct:this.data.productList[param.index]
    })
  },
  xJoin:function(){
    let that = this
    let param = that.data.productList[that.data.current]
    param.pay = param.need_payment
    if(param.need_payment){
      param.count =param.user_order_count?param.user_order_count:0 
    }else{
      param.count = param.free_program? param.free_program.program_count:0
    }
    param.index = that.data.current
    if(!param.pay && param.count >0 ){
      wx.showToast({
        title: '已加入，无法再次加入',
        icon:'none'
      })
      return
    }
    if(param.pay && param.count >0){
      wx.showToast({
        title: '已购买，无法再次购买',
        icon:'none'
      })
      return
    }
    if(that.data.productList[that.data.productList.length-1].user_order_count>0 && param.index < that.data.productList.length-1 ){
      wx.showToast({
        title: '无法购买',
        icon:'none'
      })
      return
    }
    wx.showModal({
      title: '确定加入'+ that.data.productList[that.data.current].name +'吗?',
      content: '',
      complete: (res) => {
        if (res.confirm) {
          if(that.data.ispay =='免费'){
            that.freeJoin()
          }else if(that.data.ispay =='付费'){
            that.paymentNext()
          }
        }
      }
    })
  },
  freeJoin:function(){
    let that = this
    wx.cloud.callFunction({
      name: 'digital_therapy_extend',
      data: {
        action: "open_free_program"
      }
    }).then(res => {
      wx.showToast({
        title: res.result.message,
        icon:'none',
        success:function(){
          wx.reLaunch({
            url: '/pages/navigation/using/index',
          })
        }
      })
    })
  },
  
  paymentNext: async function () {
    let that = this
    wx.showLoading({
        title: '请稍等',
    })
    let timestamp = "" + (new Date()).getTime()
    await that.prepay(timestamp)
  },
  prepay: function (time) {
    let that = this
    let product = that.data.xProduct
    let obj={
      action: 'prepay',
      camping_period_begin_date:that.data.time,
      productName: product.name,
      price: that.data.xProduct.price,
      timestamp: time,
      productId: product._id,
      // planId: product.plan_id,
      // sku_id:that.data.sku_id,
    }
    wx.cloud.callFunction({
      name: 'payment',
      data: obj,
      success(res) {
        let data = res.result.payment
        that.pay(data)
      }
    })
  },
  pay: function (payback) {
    let that = this
    wx.requestPayment({
      timeStamp: payback.timeStamp,
      nonceStr: payback.nonceStr,
      package: payback.package,
      signType: 'MD5',
      paySign: payback.paySign,
      success(res) {
        wx.hideLoading({
          success: (res) => {
            wx.reLaunch({
              url: '/pages/navigation/using/index',
            })
          },
        })
      },
      fail(res) {
        console.log("支付失败", res)
        wx.hideLoading()
      },
      complete(res) {
        console.log("支付完成,complete res :", res)
        wx.hideLoading()
      }
    })
  },
  // 展开方案详情
  // isSHow:function(e){
  //   let index  =e.currentTarget.dataset.index
  //   this.setData({
  //     isIndexDetail:index
  //   })
  // },
  onHide() {

  },
  onPullDownRefresh() {

  },
  onShareAppMessage() {

  }
})